<template>
  <div>
    <transition name="fade"
                @after-leave="handleAfterLeave">
      <div class="message-container"
           v-show="visible">
        <span v-if="type === 'info'"
              class="info">{{ message }}</span>
        <div v-if="type === 'loading'"
             class="loading-wrapper">
          <Loading></Loading>
        </div>
      </div>
    </transition>

    <div class="loading-mask"
         v-if="type === 'loading'"></div>
  </div>
</template>

<script>
import Loading from '../Loading'

export default {
  name: 'Message',
  components: {
    Loading,
  },
  data () {
    return {
      visible: false,
      type: 'info',   // 两种类型 info  loading
      timer: null,
      duration: 0,
      closed: false,
    }
  },
  watch: {
    closed (newVal) {
      if (newVal) {
        this.visible = false;
      }
    }
  },
  methods: {
    handleAfterLeave () {
      this.$destroy(true);
      this.$el.parentNode.removeChild(this.$el);
    },

    clearTimer () {
      clearTimeout(this.timer);
    },

    startTimer () {
      // duration > 0 时才自动关闭
      if (this.duration > 0) {
        this.timer = setTimeout(() => {
          if (!this.closed) {
            this.close();
          }
        }, this.duration);
      }
    },

    close () {
      this.closed = true;
      if (typeof this.onClose === 'function') {
        this.onClose(this);
      }
    },
  },
  mounted () {
    this.startTimer();
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.message-container {
  position: fixed;
  display: flex;
  margin: auto;
  width: auto;
  height: auto;
  background: rgba(0, 0, 0, 0.5);
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
  z-index: 9999;
  border-radius: 0.2rem;
  font-size: 0.24rem;
  color: #fff;
  .info {
    padding: 0.1rem 0.2rem;
    min-height: 0.8rem;
    min-width: 2rem;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .loading-wrapper {
    height: 1rem;
    width: 1rem;
  }
}

.loading-mask {
  position: fixed;
  background: transparent;
  width: 100vw;
  height: 100vh;
  top: 0;
  left: 0;
  z-index: 9998;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
  opacity: 0;
}
</style>
